package org.realogic.cfm.persistence.dialect.db;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.session.Configuration;
import org.realogic.cfm.persistence.KParameter;
import org.realogic.cfm.persistence.dialect.AbstractDialect;
import org.realogic.cfm.persistence.query.QueryCondition;

/**
 * Mysql方言的实现
 */
public class MySQLDialect extends AbstractDialect {

	public String getLimitString(String sql, int offset, int limit) {
		StringBuilder stringBuilder = new StringBuilder(sql);
		stringBuilder.append(" limit ?,?");
		return stringBuilder.toString();
	}

	public boolean supportsLimit() {
		return true;
	}

	public List<ParameterMapping> newParameterMappings(MappedStatement mappedStatement, BoundSql boundSql, QueryCondition queryCondition, boolean isPaging) {
		List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>(boundSql.getParameterMappings());
		Configuration configuration = mappedStatement.getConfiguration();
		ParameterMapping.Builder builder = null;
		List<KParameter> tmpParamList = queryCondition.getParameterList();
		int size = tmpParamList == null ? 0 : tmpParamList.size();
		KParameter tmpParam = null;
		for (int i = 0; i < size; i++) {
			tmpParam = tmpParamList.get(i);
			builder = new ParameterMapping.Builder(configuration, tmpParam.getName(), tmpParam.geClassClass());
			newParameterMappings.add(builder.build());
			boundSql.setAdditionalParameter(tmpParam.getName(), tmpParam.getValueValue());
		}
		// 分页
		if (isPaging && queryCondition.isDisplayByPage()) {
			int pageSize = queryCondition.getPageSize();
			int index = (queryCondition.getPageNo() - 1) * pageSize;
			int start = index < 0 ? 0 : index;
			int end = pageSize;
			builder = new ParameterMapping.Builder(configuration, "_start_", Integer.class);
			newParameterMappings.add(builder.build());
			boundSql.setAdditionalParameter("_start_", start);
			builder = new ParameterMapping.Builder(configuration, "_end_", Integer.class);
			newParameterMappings.add(builder.build());
			boundSql.setAdditionalParameter("_end_", end);
		}
		return newParameterMappings;
	}

}
